package net.wanho.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.wanho.dto.UserDTO;
import net.wanho.entity.User;
import net.wanho.mapper.UserMapper;
import net.wanho.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Author：汤小洋
 * Date：2024-12-18 14:08
 * Description：<描述>
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    // @Autowired
    // private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        // User user = this.baseMapper.selectByUsername(username);

        // 定义条件构造器，用来封装条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("password", password);

        User user = getOne(wrapper);

        // 先判断用户是否存在

        // 再判断密码是否正确

        return user;
    }

    @Override
    public List<User> findByCondition(UserDTO userDTO) {
        // QueryWrapper<User> wrapper = new QueryWrapper<>();
        // wrapper.like(!StringUtils.isEmpty(userDTO.getUsername()), "username", userDTO.getUsername());
        // wrapper.eq(!StringUtils.isEmpty(userDTO.getPhone()), "phone", userDTO.getPhone());
        // wrapper.or().eq(!StringUtils.isEmpty(userDTO.getAddress()), "address", userDTO.getAddress());
        // wrapper.orderByDesc("id");

        // 使用Lambda语法
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getUsername, userDTO.getUsername()) // 使用方法引用，可以避免写错字段名
                .eq(!StringUtils.isEmpty(userDTO.getPhone()), User::getPhone, userDTO.getPhone())
                .eq(!StringUtils.isEmpty(userDTO.getAddress()), User::getAddress, userDTO.getAddress());


        List<User> list = list(wrapper);
        return list;
    }

    @Override
    public Page<User> findByPage(int pageNum, int pageSize, String username) {
        Page<User> page = new Page<>(pageNum, pageSize);

        this.page(page, new QueryWrapper<User>().like("username", username));
        // System.out.println(p == page);

        return page;
    }
}
